#! /usr/bin/env bash

interface=$1
channel=$2
bssid=$3
timeout=$4

if [[ ( -z "$interface" ) || ( -z "$channel" ) || ( -z "$bssid" ) ]]
then
	echo Usage: $(basename $0) interface channel bssid [timeout]
	exit
fi

if [ -z "$timeout" ]
then
	timeout=604800
fi

cd "$(dirname "$0")"
cd ..

echo $(date +"%Y-%m-%d %H:%M:%S") Identifying BSSID $bssid channel $channel

identifier=$(echo $bssid | tr '[A-Z]' '[a-z]' | tr --delete ':')

if [ -f capture/$identifier/essid.txt ]
then
	essid=$(cat capture/$identifier/essid.txt | tail --lines 1)
	echo $(date +"%Y-%m-%d %H:%M:%S") Found ESSID \"$essid\" from cache
	exit
fi

if ls capture/$identifier/????-??-??-??-??-??-??.csv &> /dev/null
then
	list=$(ls -1 --reverse capture/$identifier/????-??-??-??-??-??-??.csv)
	while read file
	do
		essid=$(cat $file | head --lines 3 | tail --lines 1 | cut -d ',' -f 14)
		essid=${essid:1}
		if [ ! -z "$essid" ]
		then
			echo $(date +"%Y-%m-%d %H:%M:%S") Found ESSID \"$essid\" from capture
			echo $essid >> capture/$identifier/essid.txt
			exit
		fi
	done <<< "$list"
fi

screen -S capture.airobot-ng -d -m screen/capture.sh $interface $channel $bssid
screen -S deauth.airobot-ng -d -m screen/deauth.sh $interface $bssid

while [[ (0 -lt $timeout) && (-z "$essid") ]]
do
	sleep 1
	timeout=$(($timeout -1))

	if ls capture/$identifier/????-??-??-??-??-??-??.csv &> /dev/null
	then
		list=$(ls -1 capture/$identifier/????-??-??-??-??-??-??.csv | tail --lines 1)
		while read file
		do
			essid=$(cat $file | head --lines 3 | tail --lines 1 | cut -d ',' -f 14)
			essid=${essid:1}
			if [ ! -z "$essid" ]
			then
				echo $(date +"%Y-%m-%d %H:%M:%S") Found ESSID \"$essid\" from reauthentication
				echo $essid >> capture/$identifier/essid.txt
				break
			fi
		done <<< "$list"
	fi
done

./script/kill.sh screen/deauth.pid
./script/kill.sh screen/capture.pid

